package com.yunxi.service.dubboService.impl.activiti;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.pagehelper.PageInfo;
import com.yunxi.activiti.pojo.ActivitiManageVO;
import com.yunxi.activiti.pojo.ActivitiResult;
import com.yunxi.activiti.pojo.ActivitiTaskVO;
import com.yunxi.activiti.service.ActivitiManageDubboService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.activiti.ActRuTask;
import com.yunxi.model.activiti.ActivitiDeploy;
import com.yunxi.model.activiti.ActivitiManage;
import com.yunxi.model.activiti.ActivitiRecord;
import com.yunxi.service.localService.activiti.*;
import com.yunxi.service.localService.sys.RoleService;
import com.yunxi.sys.pojo.RoleVO;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2019-07-15
 */
public class ActivitiManageDubboServiceImpl implements ActivitiManageDubboService {

    @Autowired
    @Qualifier(value = "activitiManageServiceImpl")
    ActivitiManageService activitiManageService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    ProcessEngine processEngine;
    @Autowired
    @Qualifier(value = "activitiDeployServiceImpl")
    ActivitiDeployService activitiDeployService;

    @Autowired
    @Qualifier(value = "activitiRecordServiceImpl")
    ActivitiRecordService activitiRecordService;
    @Autowired
    @Qualifier(value = "actRuTaskServiceImpl")
    ActRuTaskService actRuTaskService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    @Qualifier(value = "actRuExecutionServiceImpl")
    ActRuExecutionService actRuExecutionService;
    @Autowired
    TaskService taskService;

    @Autowired
    HistoryService historyService;

    @Autowired
    @Qualifier(value = "roleServiceImpl")
    RoleService roleService;

    @Override
    public ActivitiManageVO getById(Long id) throws InvocationTargetException, IllegalAccessException {
    ActivitiManage activitiManage = activitiManageService.getById(id);
    ActivitiManageVO activitiManageVO = new ActivitiManageVO();
        BeanUtils.copyProperties(activitiManage, activitiManageVO);
        return activitiManageVO;
    }

    @Override
    public void saveOrUpdate(ActivitiManageVO activitiManageVO) throws InvocationTargetException, IllegalAccessException {
        ActivitiManage activitiManage = new ActivitiManage();
        BeanUtils.copyProperties(activitiManageVO, activitiManage);
        activitiManageService.saveOrUpdate(activitiManage);
    }

    @Override
    public void removeById(Long id) {
         activitiManageService.removeById(id);
    }

    @Override
    public PageInfo<ActivitiManageVO> findPageByVO(ActivitiManageVO activitiManageVO, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {
      PageInfo<ActivitiManageVO> pageInfo = activitiManageService.pageByVo(activitiManageVO,pageNum,pageSize);
      return pageInfo;
   }

    @Override
    public void removeByListVo(List<ActivitiManageVO> activitiManageVOList) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        activitiManageService.removeByListVo(activitiManageVOList);
    }

    @Override
    public List listByVo(ActivitiManageVO activitiManageVO) {
      return activitiManageService.listByVo(activitiManageVO);
    }

    @Override
    public ApiResult deployModel(ActivitiManageVO am) {
        try {
            //此处处理文件上传
            String relativePath = "";
            Model modelData = repositoryService.getModel(am.getActivitiModelId());
            ObjectNode modelNode = (ObjectNode) new ObjectMapper()
                    .readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);

            //model含有所有流程元素

            if(model != null) {
                Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
                for(FlowElement e : flowElements) {
                    System.out.println("flowelement id:" + e.getId()
                            + "  name:" + e.getName()
                            + "  class:" + e.getClass().toString()
                    );
                }
            }
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment()
                    .name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8"))
                    .deploy();
            System.out.println(deployment.getId() + "::" + deployment.getName() + "::" +
                    deployment.getTenantId() + "::" + deployment.getDeploymentTime());
            //获取流程图
            String deploymentId = deployment.getId();
            List<String> names = repositoryService.getDeploymentResourceNames(deploymentId);
            String imageName = null;
            for (String name : names) {
                if (name.indexOf(".png") >= 0) {
                    imageName = name;
                }
            }

            //if (imageName != null) {
            //    String suffix = FileType.getSuffixByFilename(imageName);//后缀名
            //    String savePath = FileConst.getActivitiImg() + FileConst.getFilePattern();//注册申请图片保存路径及存储格式
            //    savePath = savePath + suffix;
            //    savePath = PathFormat.parse(savePath, imageName);
            //    String uploadPath = FileConst.getSavePath() + savePath;
            //    File uploadfile = new File(uploadPath);
             /*   if (!uploadfile.exists()) {
                    uploadfile.mkdirs();
                }*/
                // 通过部署ID和文件名称得到文件的输入流
            //    InputStream in = repositoryService.getResourceAsStream(deploymentId, imageName);
            //    FileUtils.copyInputStreamToFile(in, uploadfile);
            //    String dir = "uploadFiles/flow"+savePath;
            //    relativePath = FileConst.getReadPath() + savePath;//读取文件路径
            //    OSSUtil.uploadFile(dir,uploadfile);
            //    System.out.println(relativePath);
            //}

            //插入记录
            ActivitiDeploy activitiDeploy = new ActivitiDeploy();
            activitiDeploy.setActivitiModelId(am.getActivitiModelId());
            activitiDeploy.setActivitiDeployId(deployment.getId());
            activitiDeploy.setActivitiDeployImg(relativePath);
            activitiDeployService.save(activitiDeploy);
            return ResponseUtil.ok("部署成功，部署ID=" + deployment.getId());
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseUtil.fail();
    }

    @Override
    public ApiResult start(ActivitiManageVO am, LoginInfo user) {

        Map map = new HashMap();
        String deploymentId = "";
        try {
            //通过公司id,部门id,职位id,工作流类型找到最新的部署id

            ActivitiManageVO am1 = activitiManageService.getByActivitiCode(am.getActivitiCode());
            if (am1 != null) {
                deploymentId = String.valueOf(am1.getActivitiDeployId());
                ProcessDefinition processDefinition = processEngine.getRepositoryService()//与流程定义和部署对象相关的Service
                        .createProcessDefinitionQuery()//创建一个流程定义查询
                        .deploymentId(deploymentId)//使用部署对象ID查询
                        .singleResult();
                //设置参数进行办理,将任务提交到下个节点
                Map<String, Object> variables = new HashMap<String, Object>();

                variables.put("partnerCode",user.getPartnerCode());

                //设置多个键值对
                ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey(processDefinition.getKey(), am.getBusinessKey(),variables);

                System.out.println("实例Id" + processInstance.getId() + "   " + processInstance.getName() + "  " + processInstance.getProcessDefinitionId()
                        + "  " + processInstance.getActivityId());
                //插入一条记录,记录申请
                /**
                ActivitiRecord activitiRecord = new ActivitiRecord();
                activitiRecord.setApplyUserId(user.getUserId());
                activitiRecord.setAuditStatus(ConstantActiviti.AUDITING);
                activitiRecord.setApplyDate(new Date());
                activitiRecord.setActivitiStatus(ConstantActiviti.ACTIVITI_NOT_OVER);
                activitiRecord.setInstanceId(processInstance.getId());
                activitiRecordService.saveOrUpdate(activitiRecord);
                 */
                map.put("deploymentId", deploymentId);
                map.put("instanceId", processInstance.getId());
            }else{
                return ResponseUtil.fail(1000,"流程沒有发布,流程启动失效");
            }
        } catch (Exception e) {
            map.clear();
            e.printStackTrace();
        }
        return ResponseUtil.ok(map);
    }

    @Override
    public ApiResult start(String activitiCode,String businessKey, LoginInfo user) {
        ActivitiManageVO a = new ActivitiManageVO();
        a.setActivitiCode(activitiCode);
        a.setBusinessKey(businessKey);
        return start(a,user);
    }

    @Override
    public ApiResult next(ActivitiManageVO am, LoginInfo user) {
        return ResponseUtil.ok(transactTaskCustom(am,user));
    }

    @Override
    public ApiResult next(String instanceId,String taskId, String taskStatus, LoginInfo user) {

        Task task = taskService.createTaskQuery() // 创建任务查询
                .taskId(taskId) // 根据任务id查询
                .singleResult();

        ActivitiTaskVO vo = getTaskByTaskId(taskId);

        if(StringUtils.isEmpty(user.getRoleCode())){
            user.setRoleName(task.getName());
        }
        ActivitiResult ar = new ActivitiResult();
        ar.setLastTaskName("");
        if(task!=null)
        ar.setLastTaskName(task.getName());
        //processEngine.getTaskService().createTaskQuery().
        if (taskStatus.equals("AGREE")) {
            if(task!=null){
                //同意办理 本环节结束
                Map<String, Object> variables = new HashMap<String, Object>();
                //设置多个键值对
                variables.put("taskStatus", taskStatus);
                processEngine.getRuntimeService().setVariables(instanceId,variables);
                processEngine.getTaskService().complete(taskId);
                /**判断流程是否结束，查询正在执行的执行对象表*/
                ProcessInstance rpi = processEngine.getRuntimeService()//
                        .createProcessInstanceQuery()//创建流程实例查询对象
                        .processInstanceId(instanceId)//流程实例ID
                        .singleResult();
                //说明流程实例结束了
                if (rpi == null) {
                    /**查询历史，获取流程的相关信息*/
                    HistoricProcessInstance hpi = processEngine.getHistoryService()//
                            .createHistoricProcessInstanceQuery()//
                            .processInstanceId(instanceId)//使用流程实例ID查询
                            .singleResult();
                    System.out.println(hpi.getId() + "    " + hpi.getStartTime() + "   " + hpi.getEndTime() + "   " + hpi.getDurationInMillis());
                    //插入一条记录
                    ar.setAuditStatus(Constant.AUDIT_AGREE);
                    ar.setActivitiStatus(Constant.ACTIVITI_OVER);
                }

                List<ActRuTask> nextStep = actRuTaskService.listByInstanceId(instanceId);
                if(nextStep.size()==0){
                    //流程结束
                    saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE,instanceId,taskId, user);
                    ar.setAuditStatus(Constant.AUDIT_AGREE);
                    ar.setActivitiStatus(Constant.ACTIVITI_OVER);
                }else{
                    //流程未结束
                    saveActivitiRecord(Constant.ACTIVITI_NOT_OVER, Constant.AUDIT_AGREE,instanceId,taskId, user);
                    ar.setNextTaskList(nextStep);
                }
            }
        }
        else if(taskStatus.equals("REFUSE")){
            if(task!=null){
                Map<String, Object> variables = new HashMap<String, Object>();
                //设置多个键值对
                variables.put("taskStatus", taskStatus);

                Execution execution1 = processEngine.getRuntimeService()
                        .createExecutionQuery()
                        .processInstanceId(instanceId)//流程实例ID
                        .activityId(task.getTaskDefinitionKey())//当前活动的名称
                        .singleResult();
                if(execution1!=null)
                processEngine.getRuntimeService().setVariable(execution1.getId(),"taskStatus",taskStatus);

                processEngine.getTaskService().complete(taskId);

                List<ActRuTask> nextStep = actRuTaskService.listByInstanceId( instanceId);
                if(nextStep.size()==0){
                    //流程结束
                    saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_REFUSE, instanceId, taskId,user);
                    ar.setAuditStatus(Constant.AUDIT_REFUSE);
                    ar.setActivitiStatus(Constant.ACTIVITI_OVER);
                }else{

                }
            }
        }
        else {
            //拒绝办理
            // runtimeService.suspendProcessInstanceById(instanceId);
            runtimeService.deleteProcessInstance(instanceId,"");
            saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_REFUSE,instanceId, taskId, user);
            System.out.println("冻结暂停流程实例,也可激活,并没有真正结束,冻结后没法办理任务,冻结后后面的办理人不能查看该任务");
            ar.setAuditStatus(Constant.AUDIT_REFUSE);
            ar.setActivitiStatus(Constant.ACTIVITI_OVER);
        }
        return ResponseUtil.ok(ar);
    }

    /**
     * 保存审核备注信息
     * @param instanceId
     * @param taskId
     * @param taskStatus
     * @param user
     * @param remark
     * @return
     */
    @Override
    //@Transactional
    public ApiResult next(String instanceId, String taskId, String taskStatus, LoginInfo user, String remark) {
        ActivitiResult ar = new ActivitiResult();

        if (taskStatus.equals("AGREE")) {
            //同意办理 本环节结束
            processEngine.getTaskService().complete(taskId);
            /**判断流程是否结束，查询正在执行的执行对象表*/
            ProcessInstance rpi = processEngine.getRuntimeService()//
                    .createProcessInstanceQuery()//创建流程实例查询对象
                    .processInstanceId(instanceId)//流程实例ID
                    .singleResult();
            //说明流程实例结束了
            if (rpi == null) {
                /**查询历史，获取流程的相关信息*/
                HistoricProcessInstance hpi = processEngine.getHistoryService()//
                        .createHistoricProcessInstanceQuery()//
                        .processInstanceId(instanceId)//使用流程实例ID查询
                        .singleResult();
                System.out.println(hpi.getId() + "    " + hpi.getStartTime() + "   " + hpi.getEndTime() + "   " + hpi.getDurationInMillis());
                //插入一条记录
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, instanceId, taskId, user,remark);
                ar.setAuditStatus(Constant.AUDIT_AGREE);
                ar.setActivitiStatus(Constant.ACTIVITI_OVER);
                ar.setMess("流程结束");
            }

            List nextStep = actRuTaskService.listByInstanceId(instanceId);
            if(nextStep.size()>0){
                //流程未结束
                saveActivitiRecord(Constant.ACTIVITI_NOT_OVER, Constant.AUDIT_AGREE,instanceId, taskId, user);
                ar.setNextTaskList(nextStep);
                ar.setMess("流程未结束");
            }
        } else {
            //拒绝办理
            // runtimeService.suspendProcessInstanceById(instanceId);
            runtimeService.deleteProcessInstance(instanceId,"");
            saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_REFUSE,instanceId, taskId ,user,remark);
            System.out.println("冻结暂停流程实例,也可激活,并没有真正结束,冻结后没法办理任务,冻结后后面的办理人不能查看该任务");
            ar.setAuditStatus(Constant.AUDIT_REFUSE);
            ar.setActivitiStatus(Constant.ACTIVITI_OVER);
        }
        return ResponseUtil.ok(ar);
    }

    @Override
    public ApiResult pageWait(ActivitiManageVO am, LoginInfo loginInfo) {
        Map map = new HashMap();
        map.put("partnerCode",loginInfo.getPartnerCode());
        map.put("roleCode",loginInfo.getRoleCode());
        return ResponseUtil.ok(activitiManageService.waitList(map));
    }

    /**
     * 新办理任务
     * transact
     */
    public ActivitiResult transactTaskCustom(ActivitiManageVO am, LoginInfo user) {

        ActivitiResult ar = new ActivitiResult();

        if (am.getTaskStatus().equals("AGREE")) {
            //同意办理 本环节结束
            processEngine.getTaskService().complete(am.getTaskId());
            /**判断流程是否结束，查询正在执行的执行对象表*/
            ProcessInstance rpi = processEngine.getRuntimeService()//
                    .createProcessInstanceQuery()//创建流程实例查询对象
                    .processInstanceId(am.getInstanceId())//流程实例ID
                    .singleResult();
            //说明流程实例结束了
            if (rpi == null) {
                /**查询历史，获取流程的相关信息*/
                HistoricProcessInstance hpi = processEngine.getHistoryService()//
                        .createHistoricProcessInstanceQuery()//
                        .processInstanceId(am.getInstanceId())//使用流程实例ID查询
                        .singleResult();
                System.out.println(hpi.getId() + "    " + hpi.getStartTime() + "   " + hpi.getEndTime() + "   " + hpi.getDurationInMillis());
                //插入一条记录
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, am.getInstanceId(), am.getTaskId() ,user);

                ar.setAuditStatus(Constant.AUDIT_AGREE);//同意
                ar.setActivitiStatus(Constant.ACTIVITI_OVER);//流程走完
                return ar;
            }

            List nextStep = actRuTaskService.listByInstanceId(am.getInstanceId());
            if(nextStep.size()==0){
                //流程结束
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE,am.getInstanceId(), am.getTaskId() ,user);
                ar.setAuditStatus(Constant.AUDIT_AGREE);//同意
                ar.setActivitiStatus(Constant.ACTIVITI_OVER);//流程走完
                return ar;
            }else{
                //流程未结束
                saveActivitiRecord(Constant.ACTIVITI_NOT_OVER, Constant.AUDIT_AGREE,am.getInstanceId(),am.getTaskId() , user);
                ar.setNextTaskList(nextStep);
            }
        } else if(am.getTaskStatus().equals("END")){
            //拒绝办理
            // runtimeService.suspendProcessInstanceById(instanceId);
            runtimeService.deleteProcessInstance(am.getInstanceId(),"");
            saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_REFUSE,am.getInstanceId(),am.getTaskId() ,  user);
            System.out.println("冻结暂停流程实例,也可激活,并没有真正结束,冻结后没法办理任务,冻结后后面的办理人不能查看该任务");
            ar.setAuditStatus(Constant.AUDIT_AGREE);//同意
            ar.setActivitiStatus(Constant.ACTIVITI_OVER);//流程走完
            return ar;
        }else if(am.getTaskStatus().equals("LAST")){
            //走上一步
        }

        ar.setAuditStatus(Constant.AUDIT_AGREE);//同意
        ar.setActivitiStatus(Constant.ACTIVITI_NOT_OVER);//流程走完
        return ar;
    }

    //保存审核记录
    public void saveActivitiRecord(Integer activitiStatus,
                                   Integer auditStatus,
                                   String instanceId, String taskId,LoginInfo user) {
        this.saveActivitiRecord(activitiStatus,auditStatus, instanceId, taskId,user,"");
    }

    public void saveActivitiRecord(Integer activitiStatus,
                                   Integer auditStatus,
                                   String instanceId, String taskId,LoginInfo user,String remark) {
           // Object staff = user.getStaff();
            //StaffVO staffVO = new StaffVO();
            //BeanUtils.copyProperties(staff,staffVO);

            if(remark==null) remark="";

            ActivitiRecord activitiRecord = new ActivitiRecord();
            activitiRecord.setAuditUserId(user.getUserCode());
            activitiRecord.setAuditStatus(auditStatus);
            activitiRecord.setAuditDate(new Date());
            activitiRecord.setActivitiStatus(activitiStatus);
            activitiRecord.setInstanceId(instanceId);
            activitiRecord.setTaskId(taskId);
            //activitiRecord.setPositionCode(staffVO.getPositionCode());

            if(user.getRoleCode()==null){
                if(user.getSubMap()!=null){
                    List roleList = (List)user.getSubMap().get("roleList");
                    if(roleList!=null){
                        JSONObject role = (JSONObject)roleList.get(0);
                        user.setRoleCode(role.getString("roleCode"));
                    }
                }
            }

            activitiRecord.setRoleCode(user.getRoleCode());
            activitiRecord.setAuditDesc(remark);
            if(auditStatus==Constant.AUDIT_AGREE&&remark.equals("")){
                activitiRecord.setAuditDesc("同意");
            }else if(auditStatus==Constant.AUDIT_REFUSE&&remark.equals("")){
                activitiRecord.setAuditDesc("驳回");
            }
            if(user.getRoleCode()!=null){
                RoleVO rv = roleService.getByRoleCode(user.getRoleCode());
                activitiRecord.setRoleName(rv.getRoleName());
            }else{
                activitiRecord.setRoleName(user.getRoleName());
            }
            activitiRecordService.save(activitiRecord);
    }

    /**
     * 查询个人任务列表
     */
    public List getTaskList(LoginInfo loginInfo) {
        //获取任务查询对象
        TaskQuery query = taskService.createTaskQuery();
        //组任务过滤
        query.taskCandidateGroup(loginInfo.getRoleCode());//"1000015"
        //查询任务集合
        //将list返回到前端,前端办理任务是传taskId
        List<Task> list = query.list();
        //查询需要授权的流程
        return list;
    }

    /**
     * 获取审核的详细信息
     */
    public List listByInstanceId(String instanceId) {
        List<Map> list = activitiRecordService.listByInstanceId(instanceId);
        return list;
    }

    @Override
    public ApiResult last(ActivitiManageVO am, LoginInfo user) {
        return null;
    }

    @Override
    public ActivitiResult next(String businessKey, String taskStatus, LoginInfo user) {
        ActivitiResult ar = new ActivitiResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
        List<Task> taskList = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).list();

        if(taskStatus.equals("AGREE")){
            for (int i=0;i<taskList.size();i++){
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, processInstance.getProcessInstanceId(),taskList.get(i).getId(), user);
                processEngine.getTaskService().complete(taskList.get(i).getId());
            }

            List<ActRuTask> nextStep = actRuTaskService.listByInstanceId( processInstance.getProcessInstanceId());
            if(nextStep.size()==0){
                //流程结束
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, processInstance.getProcessInstanceId(),nextStep.get(0).getId(), user);
                ar.setAuditStatus(Constant.AUDIT_AGREE);
                ar.setActivitiStatus(Constant.ACTIVITI_OVER);
            }
        }else{

        }
        //ar.setActivitiStatus(Constant.ACTIVITI_OVER);//流程走完
        return ar;
    }

    @Override
    public ActivitiResult next2step(String businessKey, String taskStatus, LoginInfo user, String nextTaskName) {
        ActivitiResult ar = new ActivitiResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
        List<Task> taskList = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).list();
        String instanceId = processInstance.getProcessInstanceId();
        if(taskStatus.equals("AGREE")){

            for (int i=0;i<taskList.size();i++){
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, instanceId,taskList.get(i).getId(), user);
                processEngine.getTaskService().setVariable(taskList.get(i).getId(),"taskStatus",taskStatus);
                processEngine.getTaskService().complete(taskList.get(i).getId());
            }

            List<ActRuTask> nextStep = actRuTaskService.listByInstanceId( instanceId);
            if(nextStep.size()==0){
                //流程结束
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, instanceId, nextStep.get(0).getId(), user);
                ar.setAuditStatus(Constant.AUDIT_AGREE);
                ar.setActivitiStatus(Constant.ACTIVITI_OVER);
            }else{
            }
        }else{
            for (int i=0;i<taskList.size();i++){
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, instanceId,taskList.get(i).getId(), user);
                processEngine.getTaskService().setVariable(taskList.get(i).getId(),"taskStatus",taskStatus);
                processEngine.getTaskService().complete(taskList.get(i).getId());
            }

            List<ActRuTask> nextStep = actRuTaskService.listByInstanceId( instanceId);
            if(nextStep.size()==0){
                //流程结束
                saveActivitiRecord(Constant.ACTIVITI_OVER, Constant.AUDIT_AGREE, instanceId,nextStep.get(0).getId(), user);
                ar.setAuditStatus(Constant.AUDIT_AGREE);
                ar.setActivitiStatus(Constant.ACTIVITI_OVER);
            }else{

            }
        }
        return ar;
    }

    @Override
    public ActivitiTaskVO getCurTaskIdByBusinessKey(String orderCustomerId) {
        return activitiManageService.getCurTaskIdByBusinessKey(orderCustomerId);
    }

    @Override
    public String getInstanceIdByBusinessKey(String businessKey) {
        return activitiManageService.getInstanceIdByBusinessKey(businessKey);
    }

    @Override
    public List listRecordByInstanceId(String instanceId) {
        List<Map> list = activitiRecordService.listByInstanceId(instanceId);
        return list;
    }

    @Override
    public List<ActivitiTaskVO> listInstanceNodeByBusinessKey(String businessKey) {
        return activitiManageService.listInstanceNodeByBusinessKey(businessKey);
    }

    @Override
    public List<ActivitiTaskVO> listInstanceNodeByInstanceId(String instanceId) {
        return activitiManageService.listInstanceNodeByInstanceId(instanceId);
    }

    @Override
    public List listRecordByBusinessKey(String businessKey) {
        return activitiManageService.listRecordByBusinessKey(businessKey);
    }

    @Override
    public ApiResult stopActivitiByBusinessKey(String businessKey) {

        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).list();

        for(int i=0;i<list.size();i++){
            ProcessInstance processInstance = (ProcessInstance)list.get(i);
            if(processInstance!=null){
                runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(),"");
                return ResponseUtil.ok("流程删除成功");
            }
        }
        return ResponseUtil.ok("流程删除失败");
    }

    public ActivitiTaskVO getTaskByTaskId(String taskId){
        return activitiManageService.getTaskByTaskId(taskId);
    }

    public ActivitiTaskVO getHisTaskByTaskId(String taskId){
        return activitiManageService.getHisTaskByTaskId(taskId);
    }
}
